package com.cskaoyan.mall.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * User: zsquirrel
 * Date: 2020/4/28
 * Time: 4:15 下午
 */
@WebFilter("/api/mall/*")
public class MallFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin","http://localhost:8085");
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials","true");
        String method = request.getMethod();
//        if(!"OPTIONS".equals(method)){
//            String requestURI = request.getRequestURI();
//            if(auth(requestURI)){
//                HttpSession session = request.getSession();
//                System.out.println("filter:" + session + " " + requestURI + " :" + request.getMethod());
//                System.out.println("filter:" + session.getId() + " " + requestURI + " :" + request.getMethod());
//                String email = (String) session.getAttribute("email");
////                if(email == null){
////                    Result result = new Result();
////                    result.setCode(10000);
////                    result.setMessage("当前接口没有登录拒绝访问");
////                    response.getWriter().println(new Gson().toJson(result));
////                    return;
////                }
//            }
//        }
        chain.doFilter(request, response);
    }

    /**
     * 判断当前请求的url是否需要进行权限验证
     * 除了登录以外，都应当设置拦截
     * @param requestURI
     * @return
     */
    private boolean auth(String requestURI) {
        if("/api/admin/admin/login".equals(requestURI)){
            return false;
        }
        return true;
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
